#include "change.h"
#include "sbconstants.h"

#include <iostream>

Change::Change()
{
}

Change::Change(sf::Uint32 timestamp, sf::Uint32 number) :
	timestamp(timestamp), number(number), type(MESSAGE::WORLD_UPDATE::CONFIRMED)
{
}

Change::Change(sf::Uint32 timestamp, sf::Uint32 number, const GameObject& object) :
	timestamp(timestamp), number(number), type(MESSAGE::WORLD_UPDATE::CREATE_OBJ)
{
	newObject = new GameObject(object);
}

Change::Change(sf::Uint32 timestamp, sf::Uint32 number, sf::Uint32 objectID) :
	timestamp(timestamp), number(number), type(MESSAGE::WORLD_UPDATE::DESTROY_OBJ)
{
	destoyedObjectID = objectID;
}

Change::Change(sf::Uint32 timestamp, sf::Uint32 number, sf::Uint32 shipID, sf::Uint8 controls) :
	timestamp(timestamp), number(number), type(MESSAGE::WORLD_UPDATE::SHIP_CONTROL)
{
	shipControl.shipID = shipID;
	shipControl.controls = controls;
}

Change::~Change()
{
	if (type == MESSAGE::WORLD_UPDATE::CREATE_OBJ)
	{
		delete newObject;
	}
}



sf::Packet& operator <<(sf::Packet& packet, const Change& obj)
{
	packet << obj.timestamp << obj.number << obj.type;
	switch (obj.type)
	{
		case MESSAGE::WORLD_UPDATE::CONFIRMED:
			break;

		case MESSAGE::WORLD_UPDATE::CREATE_OBJ:
			packet << (*(obj.newObject));
			break;

		case MESSAGE::WORLD_UPDATE::DESTROY_OBJ:
			packet << obj.destoyedObjectID;
			break;

		case MESSAGE::WORLD_UPDATE::SHIP_CONTROL:
			packet << obj.shipControl.shipID << obj.shipControl.controls;
			break;
	}
	return packet;
}

sf::Packet& operator >>(sf::Packet& packet, Change& obj)
{
	packet >> obj.timestamp >> obj.number >> obj.type;
	switch (obj.type)
	{
		case MESSAGE::WORLD_UPDATE::CONFIRMED:
			break;

		case MESSAGE::WORLD_UPDATE::CREATE_OBJ:
			obj.newObject = new GameObject();
			packet >> (*(obj.newObject));
			break;
		case MESSAGE::WORLD_UPDATE::DESTROY_OBJ:
			packet >> obj.destoyedObjectID;
			break;
		case MESSAGE::WORLD_UPDATE::SHIP_CONTROL:
			packet >> obj.shipControl.shipID >> obj.shipControl.controls;
			break;
	}
	return packet;
}

